package net.caixiaomi.info.ui.dialog;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.view.SupportMenuInflater;
import android.support.v7.view.menu.MenuBuilder;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;

import net.caixiaomi.info.R;
import net.caixiaomi.info.adapter.ShareAdapter;
import net.caixiaomi.info.app.CommonApp;
import net.caixiaomi.info.base.BaseDialogFragment;
import net.caixiaomi.info.base.quickadapter.BaseQuickAdapter;
import net.caixiaomi.info.helper.AppHelper;
import net.caixiaomi.info.model.ShareItem;
import net.caixiaomi.info.model.ShareModel;
import net.caixiaomi.info.util.Constants;
import net.caixiaomi.info.util.ToastUtil;
import net.caixiaomi.info.util.WeiXinUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class ShareDialogFragment extends BaseDialogFragment implements BaseQuickAdapter.OnItemClickListener {
    @BindView(android.R.id.list)
    RecyclerView mListView;

    private ShareAdapter mAdapter;
    private ShareModel mShareModel;
    private Bitmap mBitmap;

    @Override
    protected int layoutRes() {
        return R.layout.dialog_share;
    }

    @OnClick(R.id.btn_cancel)
    void toCancle() {
        dismissAllowingStateLoss();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            boolean dealVersion = CommonApp.STORE.getBoolean(Constants.KEY_DEAL_VERSION, false);
            String strData = getArguments().getString("data");
            mShareModel = JSON.parseObject(strData, ShareModel.class);
            StringBuilder url = new StringBuilder(mShareModel.getUrl());
            if (url.indexOf("?") < 0) {
                url.append("?");
            } else {
                url.append("&");
            }
            url.append("frz=").append(dealVersion ? "1" : "0");
            mShareModel.setUrl(url.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onViewCreated(@NonNull View view) {
        Window window = getDialog().getWindow();
        WindowManager.LayoutParams wlp = window.getAttributes();
        wlp.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wlp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        wlp.gravity = Gravity.BOTTOM;
        window.setAttributes(wlp);
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        window.setBackgroundDrawable(new ColorDrawable(0xff000000));
        getDialog().getWindow().setLayout(dm.widthPixels, getDialog().getWindow().getAttributes().height);

        MenuInflater menuInflater = new SupportMenuInflater(getContext());
        MenuBuilder menuBuilder = new MenuBuilder(getContext());
        menuInflater.inflate(R.menu.share_menu, menuBuilder);
        List<ShareItem> items = new ArrayList<>();
        for (int index = 0; index < menuBuilder.size(); index++) {
            MenuItem item = menuBuilder.getItem(index);
            items.add(new ShareItem(item.getItemId(), item.getTitle().toString(), item.getIcon()));
        }
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) mListView.getLayoutParams();
        layoutParams.topMargin = (int) getResources().getDimension(R.dimen.padding_30);
        layoutParams.bottomMargin = layoutParams.topMargin;

        mListView.setLayoutManager(new GridLayoutManager(getActivity(), 4));
        mListView.setNestedScrollingEnabled(false);
        mAdapter = new ShareAdapter(R.layout.view_textview);
        mAdapter.setOnItemClickListener(this);
        mAdapter.setNewData(items);
        mListView.setAdapter(mAdapter);
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        try {
            switch (view.getId()) {
                case R.id.btn_wechat:
                case R.id.btn_wechat_friends:
                    if (!AppHelper.bApllicationInstalled("com.tencent.mm")) {
                        ToastUtil.s(R.string.C_SHARE_FAIL);
                        return;
                    }
                    if (!TextUtils.isEmpty(mShareModel.getThumbUrl())) {
                        downLoadImage(mShareModel.getThumbUrl(), view.getId());
                        return;
                    }

                    mBitmap = BitmapFactory.decodeResource(CommonApp.getInstance().getResources(), R.mipmap.ic_launcher);
                    WeiXinUtils.shareUrl(getActivity(), mShareModel.getUrl(), mShareModel.getTitle(), mShareModel.getDescription(), mBitmap, view.getId() == R.id.btn_wechat ? SendMessageToWX.Req.WXSceneSession : SendMessageToWX.Req.WXSceneTimeline);
                    break;
                case R.id.btn_copy:
                    AppHelper.copy2Clipboard(mShareModel.getUrl());
                    ToastUtil.s(R.string.C_COPY_DONE);
                    break;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void downLoadImage(final String url, final int shareId) {

        AppHelper.asynExecute(new Runnable() {
            @Override
            public void run() {
                try {
                    if (!TextUtils.isEmpty(url)) {
                        mBitmap = Glide.with(CommonApp.getInstance()).asBitmap()
                                .load(url)
                                .submit(WeiXinUtils.THUMB_SIZE, WeiXinUtils.THUMB_SIZE)
                                .get();
                        WeiXinUtils.shareUrl(getActivity(), mShareModel.getUrl(), mShareModel.getTitle(), mShareModel.getDescription(), mBitmap, shareId == R.id.btn_wechat ? SendMessageToWX.Req.WXSceneSession : SendMessageToWX.Req.WXSceneTimeline);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });


    }


}
